<template>
  <div>
    <a-card v-only-admin>
      <h2>用户管理</h2>
      <a-divider />
      <space-between>
        <div class="search">
          <a-input-search
            v-model:value="keyword"
            placeholder="根据用户名搜索"
            enter-button
            @search="onSearch"
          />
          <a v-show="isCleared" @click="onClear">清除</a>
        </div>
        <a-button @click="addUser" type="primary">添加用户</a-button>
      </space-between>
      <a-divider />
      <a-table
        :dataSource="userlist"
        :columns="columns"
        :pagination="false"
        bordered
      >
        <template #createdAt="data">
          {{ formateTimestamp(data.record.meta.createdAt) }}
        </template>
        <template #character="data">
          <a @click="editCharacter(data.record)"><EditOutlined /></a>
          {{ getCharacterInfoById(data.record.character).title }}
        </template>
        <template #operration="data">
          <a @click="resetPassword(data.record._id)">重置密码</a>&nbsp;
          <a @click="deleteUser(data.record._id)">删除</a>
        </template>
      </a-table>
      <!-- 用户表格分页组件 -->
      <div class="mt-10">
        <a-pagination
          v-model:current="curPage"
          :page-size="pageSize"
          :total="total"
          @change="setPage"
        ></a-pagination>
      </div>
    </a-card>
    <add-one v-model:show="addoneVisible" @update="getUserlist" />
    <!-- 修改角色弹框 -->
    <a-modal v-model:visible="showEditCharacter" title="修改角色" @ok="onOk">
      <a-select v-model:value="editForm.character" style="width:300px">
        <a-select-option
          v-for="item in characterInfo"
          :key="item._id"
          :value="item._id"
        >
          {{ item.title }}
        </a-select-option>
      </a-select>
    </a-modal>
  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import { EditOutlined } from '@ant-design/icons-vue'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import store from '../../store'
import { handleResult, formateTimestamp } from '../../helpers/utils'
import { getCharacterInfoById } from '../../helpers/character'
import { userService } from '../../services'
import AddOne from './AddOne.vue'
export default defineComponent({
  components: {
    AddOne,
    EditOutlined
  },
  setup () {
    const userlist = ref([])
    const curPage = ref(1)
    const pageSize = ref(5)
    const total = ref(0)
    const columns = [
      {
        title: '用户名称',
        dataIndex: 'username'
      },
      {
        title: '注册时间',
        slots: {
          customRender: 'createdAt'
        }
      },
      {
        title: '角色',
        slots: {
          customRender: 'character'
        }
      },
      {
        title: '操作',
        slots: {
          customRender: 'operration'
        }
      }
    ]

    const setPage = page => {
      curPage.value = page
      getUserlist()
    }

    /** 获取用户列表信息 */
    const getUserlist = async () => {
      const res = await userService.getUserlist(
        curPage.value,
        pageSize.value,
        keyword.value
      )
      handleResult(res).success(({ data: { list, total: t } }) => {
        list.forEach(item => (item.key = item._id))
        userlist.value = list
        total.value = t
      })
    }

    onMounted(async () => {
      getUserlist()
    })

    /** 重置用户密码 */
    const resetPassword = async userId => {
      console.log(userId)
      const res = await userService.resetPassword(userId)
      handleResult(res).success(({ msg }) => {
        message.success(msg)
      })
    }

    const addoneVisible = ref(false)

    /** 添加用户 */
    const addUser = () => {
      addoneVisible.value = true
    }

    /** 删除用户 */
    const deleteUser = async userId => {
      const res = await userService.deleteUser(userId)
      handleResult(res).success(({ msg }) => {
        message.success(msg)
        getUserlist()
      })
    }

    // =================== 搜索相关业务 begin =================== //
    const keyword = ref('')
    const isCleared = ref(false)
    /** 点击清除事件 */
    const onClear = () => {
      isCleared.value = false
      keyword.value = ''
      getUserlist()
    }
    /** 点击搜索事件 */
    const onSearch = () => {
      if (keyword.value !== '') {
        isCleared.value = true
      }
      getUserlist()
    }

    // ==================== 搜索相关业务 end ==================== //

    const showEditCharacter = ref(false)

    /** 编辑角色表单 */
    const editForm = reactive({
      character: '',
      current: {}
    })

    const editCharacter = record => {
      editForm.current = record
      editForm.character = record.character
      showEditCharacter.value = true
    }
    /** 确定修改角色 */
    const onOk = async () => {
      const res = await userService.updateCharacter(
        editForm.character,
        editForm.current._id
      )
      handleResult(res).success(({ msg }) => {
        message.success(msg)
        showEditCharacter.value = false
        editForm.current.character = editForm.character
      })
    }

    const { characterInfo } = store.state

    return {
      userlist,
      curPage,
      pageSize,
      total,
      columns,
      setPage,
      formateTimestamp,
      resetPassword,
      deleteUser,
      addoneVisible,
      addUser,
      getUserlist,
      keyword,
      isCleared,
      onClear,
      onSearch,
      getCharacterInfoById,
      editCharacter,
      showEditCharacter,
      characterInfo,
      editForm,
      onOk
    }
  }
})
</script>

<style lang="scss" scoped>
.search {
  width: 300px;
  display: flex;
  align-items: center;
  a {
    margin-left: 12px;
    width: 40px;
  }
}
</style>
